//
//  MyViewController.m
//  NeteaseNewsLY
//
//  Created by dllo on 16/1/22.
//  Copyright © 2016年 www.lanou3g.com 蓝鸥科技. All rights reserved.
//

#import "MyViewController.h"
#import "AppDelegate.h"

@interface MyViewController ()<UITableViewDelegate, UITableViewDataSource,UIAlertViewDelegate>

@property (nonatomic, retain)UITableView *tableView;
@property (nonatomic, retain)NSArray *dataArr;

@property (nonatomic, retain)UIView *loginView;
@property (nonatomic, retain)UIView *blackView;
// 头像/用户名
@property (nonatomic, retain)UIImageView *headImg;
@property (nonatomic, retain)UILabel *userLabel;
@end

@implementation MyViewController
- (void)dealloc
{
    [_tableView release];
    [_dataArr release];
    [_loginView release];
    [_blackView release];
    [super dealloc];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    self.view.backgroundColor = [UIColor whiteColor];
    
    // 导航栏颜色
    self.navigationController.navigationBar.barTintColor = [UIColor redColor];
    // 导航栏上按钮颜色
    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
    // 坐标从左上角开始
    self.navigationController.navigationBar.translucent = NO;
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"退出" style:UIBarButtonItemStyleDone target:self action:@selector(tapBreak:)];
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, WIDTH * 375, HEIGHT * 600) style:UITableViewStylePlain];
   
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [self.view addSubview:_tableView];
    [_tableView release];
    
    [_tableView registerClass:[MyCell class] forCellReuseIdentifier:@"cell"];
    // 登录区域
    self.loginView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, WIDTH * 375, HEIGHT * 200)];
    _loginView.backgroundColor = [UIColor redColor];
    [self.view addSubview:_loginView];
    [_loginView release];
    _loginView.layer.borderWidth = 1;
    // 创建头部视图
    [self createLoginView];
    
    self.tableView.tableHeaderView = _loginView;
    
    self.dataArr = @[@"我的收藏", @"夜间模式", @"清除缓存", @"本地推送", @"意见反馈", @"检测新版本",@"关于"];
    
    // 夜间模式
    AppDelegate *delegate = [[UIApplication sharedApplication] delegate];
    self.blackView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, WIDTH * 375, HEIGHT * 667)];
    self.blackView.backgroundColor = [UIColor blackColor];
    self.blackView.alpha = 0.6;
    self.blackView.userInteractionEnabled = NO;
    [delegate.window addSubview:_blackView];
    _blackView.hidden = YES;
    [_blackView release];
    
    
}
- (void)createLoginView
{
    // 头像
    self.headImg = [[UIImageView alloc] initWithFrame:CGRectMake(WIDTH * 150, HEIGHT * 40, WIDTH * 75, HEIGHT * 75)];
    _headImg.layer.cornerRadius = 30;
    _headImg.image = [UIImage imageNamed:@"touxiang"];
    _headImg.userInteractionEnabled = YES;
    [self.loginView addSubview:_headImg];
    [_headImg release];
    // 用户名
    self.userLabel= [[UILabel alloc] initWithFrame:CGRectMake(WIDTH * 115, HEIGHT * 140, WIDTH * 150, HEIGHT * 30)];
    _userLabel.tag = 777;
    _userLabel.text = @"还没有名字哦";
    _userLabel.userInteractionEnabled = YES;
    _userLabel.textAlignment = NSTextAlignmentCenter;
    [self.loginView addSubview:_userLabel];
    [_userLabel release];
    // 创建手势
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
    [_headImg addGestureRecognizer:tap];
    UITapGestureRecognizer *tapDown = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
    [self.headImg addGestureRecognizer:tapDown];
    [_userLabel addGestureRecognizer:tapDown];
    // 显示本地内容 头像 姓名等
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject stringByAppendingPathComponent:@"userInfo.plist"];
    NSDictionary *userDic = [NSDictionary dictionaryWithContentsOfFile:path];
    // 如果存在显示
    if (userDic && ([userDic[@"uName"] length] > 0)) {
        [_headImg sd_setImageWithURL:[NSURL URLWithString:userDic[@"iconUrl"]]];
        _userLabel.text = userDic[@"uName"];
    }
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _dataArr.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    cell.textLabel.text = _dataArr[indexPath.row];
    if (indexPath.row == 1) {
        // 夜间模式
        UISwitch *kaiguan = [[UISwitch alloc] init];
        cell.accessoryView = kaiguan;
        [kaiguan addTarget:self action:@selector(kaiguanAction:) forControlEvents:UIControlEventValueChanged];
        [kaiguan release];
    }else if (indexPath.row == 3){
        // 本地推送
        UISwitch *tuisong = [[UISwitch alloc] init];
        cell.accessoryView = tuisong;
        [tuisong addTarget:self action:@selector(tuisongAction:) forControlEvents:UIControlEventTouchUpInside];
        [tuisong release];
    }
    
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        // 收藏
        ShouCangViewController *shoucang = [[ShouCangViewController alloc] init];
        [self.navigationController pushViewController:shoucang animated:YES];
        [shoucang release];
    }else if (indexPath.row == 2){
        UIAlertController *cleanAlert =[UIAlertController alertControllerWithTitle:@"确定要清除缓存吗?" message:@".." preferredStyle:UIAlertControllerStyleAlert ];
        //获取缓存大小路径
        NSString *cashPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0];
        //计算文件夹的大小
        CGFloat fileSize = [self folderSizeAtPath:cashPath];
        //计算图片的大小
        CGFloat imageSize = [[SDImageCache sharedImageCache] getSize];
        dispatch_async(dispatch_get_main_queue(), ^{
            //总共的缓存大小
            CGFloat m = fileSize + imageSize/(1024.0*1024.0);
            cleanAlert.message  = [NSString stringWithFormat:@"%.2fMB",m];
            [self.tableView reloadData];
            
        });
        //取消按钮
        UIAlertAction *cancell = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
        //确定按钮
        UIAlertAction *ok = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            //文件夹清缓存
            [self clean:cashPath];
            //sdimage 清缓存
            [[SDImageCache sharedImageCache] cleanDisk];
        }];
        
        [cleanAlert addAction:cancell];
        [cleanAlert addAction:ok];
        //弹窗出现
        [self presentViewController:cleanAlert animated:YES completion:nil];
    }else if (indexPath.row == 4){
        // 意见反馈
        FankuiViewController *fankui = [[FankuiViewController alloc] init];
        [self.navigationController pushViewController:fankui animated:YES];
        [fankui release];
    }else if (indexPath.row == 5){
        // 网易新闻检测新版本
        NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
        CFShow(infoDictionary);
        // app名称
        NSString *app_Name = [infoDictionary objectForKey:@"CFBundleDisplayName"];
        // app版本
        NSString *app_Version = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
        // app build版本
        NSString *app_build = [infoDictionary objectForKey:@"CFBundleVersion"];
        
        UIAlertController *bbAlert =[UIAlertController alertControllerWithTitle:app_Name message:app_Version preferredStyle:UIAlertControllerStyleAlert];
        // 弹窗出现
        [self presentViewController:bbAlert animated:YES completion:nil];
        [self performSelector:@selector(diss) withObject:bbAlert afterDelay:1];
        
    }else if (indexPath.row == 6) {
        AboutViewController *aboutVC = [[AboutViewController alloc] init];
        [self.navigationController pushViewController:aboutVC animated:YES];
        [aboutVC release];
    }
}
- (void)kaiguanAction:(UISwitch *)kaiguan
{
    if (kaiguan.isOn) {
        NSLog(@"切换到夜间模式");
        self.blackView.hidden = NO;
    }else{
        NSLog(@"切换到白天模式");
        self.blackView.hidden = YES;
    }
    
}
// 本地推送
- (void)tuisongAction:(UISwitch *)tuisong
{
    if (tuisong.isOn) {
        UILocalNotification *notification = [[[UILocalNotification alloc] init] autorelease];
        // 设置2秒之后
        NSDate *push = [NSDate dateWithTimeIntervalSinceNow:3];
        if (notification != nil) {
            // 设置推送时间
            notification.fireDate = push;
            // 设置时区
            notification.timeZone = [NSTimeZone defaultTimeZone];
            // 设置重复间隔
            notification.repeatInterval = kCFCalendarUnitDay;
            // 推送声音
            notification.soundName = UILocalNotificationDefaultSoundName;
            // 推送内容
            notification.alertBody = @"推送内容";
            // 显示在icon上的红色圈子的数字
            notification.applicationIconBadgeNumber = 1;
            // 设置userinfo 方便在之后需要撤销的时候使用
            NSDictionary *info = [NSDictionary dictionaryWithObject:@"name" forKey:@"key"];
            notification.userInfo = info;
            // ios8之后需要添加注册,才能得到授权
            if ([[UIApplication sharedApplication] respondsToSelector:@selector(registerUserNotificationSettings:)]) {
                UIUserNotificationType type = UIUserNotificationTypeAlert | UIUserNotificationTypeBadge | UIUserNotificationTypeSound;
                UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:type categories:nil];
                [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
            }
            // 添加推送到UIApplication
            UIApplication *app = [UIApplication sharedApplication];
            [app scheduleLocalNotification:notification];
        }
    }else{
        // 接触本地推送
        UIApplication *app = [UIApplication sharedApplication];
        // 获取本地推送数组
        NSArray *localArr = [app scheduledLocalNotifications];
        // 声明本地通知对象
        UILocalNotification *localNotification = nil;
        if (localArr) {
            for (UILocalNotification *noti in localArr) {
                NSDictionary *tDic = noti.userInfo;
                if (tDic) {
                    NSString *inKey = [tDic objectForKey:@"key"];
                    if ([inKey isEqualToString:@"name"]) {
                        if (localNotification) {
                            [localNotification release];
                            localNotification = nil;
                        }
                        localNotification = [noti retain];
                        break;
                    }
                }
            }
            // 判断是否找到已经存在相同key的推送
            if (!localNotification) {
                // 不存在初始化
                localNotification = [[UILocalNotification alloc] init];
            }
            if (localNotification) {
                // 不推送 取消推送
                [app cancelLocalNotification:localNotification];
                [localNotification release];
                return;
            }
        }
    }
}
//清除方法
- (void)clean:(NSString *)path{
    NSArray *files = [[NSFileManager defaultManager] subpathsAtPath:path];
    
    for (NSString *p in files) {
        
        NSError *error;
        
        NSString *Path = [path stringByAppendingPathComponent:p];
        
        if ([[NSFileManager defaultManager] fileExistsAtPath:Path]) {
            
            [[NSFileManager defaultManager] removeItemAtPath:Path error:&error];
            
        }
    }
}
//文件夹计算大小方法 遍历文件夹获得文件夹的大小  返回多少M
- (float ) folderSizeAtPath:(NSString*) folderPath{
    
    NSFileManager* manager = [NSFileManager defaultManager];
    
    if (![manager fileExistsAtPath:folderPath])
        return 0;
    
    NSEnumerator *childFilesEnumerator = [[manager subpathsAtPath:folderPath] objectEnumerator];
    
    NSString* fileName;
    
    long long folderSize = 0;
    
    while ((fileName = [childFilesEnumerator nextObject]) != nil){
        
        NSString* fileAbsolutePath = [folderPath stringByAppendingPathComponent:fileName];
        
        folderSize += [self fileSizeAtPath:fileAbsolutePath];
        
    }
    
    return folderSize/(1024.0*1024.0);
    
}
- (long long) fileSizeAtPath:(NSString*) filePath{
    
    NSFileManager* manager = [NSFileManager defaultManager];
    
    if ([manager fileExistsAtPath:filePath]){
        
        return [[manager attributesOfItemAtPath:filePath error:nil] fileSize];
        
    }
    
    return 0;
    
}
#pragma mark - 登录
- (void)tapAction:(UITapGestureRecognizer *)tap
{
    BOOL isLogin = [[NSUserDefaults standardUserDefaults] boolForKey:@"isLogin"];
    if (!isLogin) {
        [self setLoginInfo];// 登录并设置用户信息
    }else{
        // 判断是否切换用户
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"是否切换用户" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *yesAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [self setLoginInfo];// 切换用户
        }];
        UIAlertAction *noAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            
        } ];
        [alert addAction:yesAction];
        [alert addAction:noAction];
        [self presentViewController:alert animated:yesAction completion:^{
            
        }];
    }
}


#pragma mark - 友盟三方登录加设置用户信息
- (void)setLoginInfo{
    UMSocialSnsPlatform *snsPlatform = [UMSocialSnsPlatformManager getSocialPlatformWithName:UMShareToSina];
    snsPlatform.loginClickHandler(self,[UMSocialControllerService defaultControllerService], YES,^(UMSocialResponseEntity *response){
        // 获取微博用户名,uid,token等
        // 如果发送结果成功
        if (response.responseCode == UMSResponseCodeSuccess) {
            // 定义用户微博对象
            UMSocialAccountEntity *snsAccount = [[UMSocialAccountManager socialAccountDictionary] valueForKey:UMShareToSina];
            NSLog(@"username is %@, uid is %@, token is %@, url is %@", snsAccount.userName, snsAccount.usid, snsAccount.accessToken, snsAccount.iconURL);
            // 改变头像
            [_headImg sd_setImageWithURL:[NSURL URLWithString:snsAccount.iconURL]];
            // 头像设置圆角
            _headImg.layer.cornerRadius = _headImg.frame.size.width / 2;
            _headImg.clipsToBounds = YES;
            // 显示名字
            _userLabel.text = snsAccount.userName;
            // 登录状态为YES
            [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"isLogin"];
            // 存本地
            NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask, YES).lastObject stringByAppendingPathComponent:@"userInfo.plist"];
            NSDictionary *dic = @{@"uName": snsAccount.userName, @"iconUrl": snsAccount.iconURL};
            [dic writeToFile:path atomically:YES];
        }
    });

}
#pragma mark - 退出登录
- (void)tapBreak:(UITapGestureRecognizer *)tap
{
    BOOL isLogin = [[NSUserDefaults standardUserDefaults] boolForKey:@"isLogin"];
    if (isLogin) {
        // 如果已经登录则询问是否退出应用
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"是否退出登录" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *yesAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            // 删除本地信息
            NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject stringByAppendingPathComponent:@"userInfo.plist"];
            NSDictionary *dic = [NSDictionary dictionary];
            [dic writeToFile:path atomically:YES];
            // 登录状态设置为NO
            [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"isLogin"];
            [self promptViewWithMessage:@"退出成功"];
            _headImg.image = [UIImage imageNamed:@"touxiang"];
            _userLabel.text = @"还没有名字哦";
        }];
        UIAlertAction *noAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        [alert addAction:yesAction];
        [alert addAction:noAction];
        [self presentViewController:alert animated:yesAction completion:^{
            
        }];
    }else{
        [self promptViewWithMessage:@"未登录"];
    }
}
// 未登录提示
- (void)promptViewWithMessage:(NSString *)message
{
    UIView *tishi = [[UIView alloc] initWithFrame:CGRectMake(0, 0, WIDTH * 80, HEIGHT * 40)];
    tishi.center = self.view.center;
    tishi.backgroundColor = [UIColor blackColor];
    tishi.alpha = 0.5;
    tishi.layer.cornerRadius = 10;
    [self.view addSubview:tishi];
    [tishi release];
    UILabel *tishiLabel = [[UILabel alloc] initWithFrame:CGRectMake(WIDTH * 5, HEIGHT * 5, WIDTH * 70, HEIGHT * 30)];
    tishiLabel.textColor = [UIColor whiteColor];
    tishiLabel.text = message;
    [tishi addSubview:tishiLabel];
    [tishiLabel release];
    // 延时
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [tishi removeFromSuperview];
    });
}
- (void)diss
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
